﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AppSocketModel;
using AppSocketService;
using AppSocketService.Account;
using AppSocketService.Company;
using BCGPSRESTful.WebApiConfig;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using static BCGPSRESTful.TokenExtension;

namespace BCGPSRESTful.Controllers.Page.Account
{
    /// <summary>
    /// 账户控制器
    /// </summary>
    [ApiExplorerSettings(GroupName = "CompanyPage")]
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : PageBaseController
    {
        private readonly TimeSpan expiration = TimeSpan.FromDays(7);
        private readonly IAccountService accountService;

        #region 构造函数 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accountService"></param>
        public AccountController(IAccountService accountService)
        {
            this.accountService = accountService;
        }
        #endregion

        #region 测试API Test
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns> 
        [HttpGet("[action]")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(DateTime), 200)]
        public ActionResult<DateTime> Test()
        {
            return this.Ok(DateTime.Now);
        }
        #endregion

        #region 注册主账户
        /// <summary>
        /// 注册主账户
        /// </summary>
        /// <returns></returns> 
        [HttpPost("[action]")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(AccountDto), 200)]
        public ActionResult<AccountDto> Register(AccountRegisterDto accountRegisterDto)
        {
            return (accountService.RegisterNew(accountRegisterDto));
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(TokenDto), 200)]
        public ActionResult<TokenDto> Login([FromBody] AccountLoginDto dto)
        {
            var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrWhiteSpace(ip))
                ip = HttpContext.Connection.RemoteIpAddress.ToString();

            var accountDto = accountService.Login(dto, ip);
            accountDto.Password = string.Empty;
            if (accountDto == null)
                throw new ArgumentException("用户名或密码不正确!");

            bool isRealy = false;
            if (accountDto.ParentAccountId == null)
            {
                var companyService = new CompanyService();
                var companyDto = companyService.Get(accountDto.CompanyId);
                isRealy = companyDto.IsRelay;
            }
            return new TokenDto
            {
                Description = "WELCAME:" + accountDto.AccountName,
                AccessToken = accountDto.GenerateToken(expiration, accountDto.AccountRole),
                ExpiresIn = (int)expiration.TotalSeconds,
                EndTime = DateTime.Now.AddSeconds(expiration.TotalSeconds - 12 * 3600),
                Account = accountDto,
                IsRelay = isRealy 
            };
        }

        #endregion

        #region 修改账户
        /// <summary>
        /// 修改账户
        /// </summary>
        /// <param name="accountDto"></param>
        /// <returns></returns>
        [HttpPut("[action]")]
        [ProducesResponseType(typeof(AccountDto), 200)]
        public ActionResult<AccountDto> Update(AccountDto accountDto)
        {
            return accountService.Update(accountDto);
        }
        #endregion
        
        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="accountId">账户ID</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPut("[action]")]
        [ProducesResponseType(typeof(void), 200)]
        public ActionResult UpdatePassword([FromQuery (Name ="account_id")]string accountId, string password)
        {
            accountService.UpdatePassword(accountId, password);
            return this.Ok();
        }
        #endregion

        #region 获取指定账户
        /// <summary>
        /// 获取指定账户
        /// </summary>
        /// <param name="account_id">账户Id</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(AccountDto), 200)]
        public ActionResult<AccountDto> GetAccount(string account_id)
        {
            return accountService.GetAccount(account_id);
        }
        #endregion

        #region 添加子账户
        /// <summary>
        /// 添加子账户
        /// </summary>
        /// <param name="accountRequestDto"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        [ProducesResponseType(typeof(AccountDto), 200)]
        public AccountDto AddSubAccount(AccountRequestDto   accountRequestDto)
        {
            return accountService.AddNewSubAccount(accountRequestDto);
        }
        #endregion

        #region 获取子账户列表
        /// <summary>
        /// 获取子账户列表
        /// </summary>
        /// <param name="accountId">账户Id</param>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(List<AccountDto>), 200)]
        public ActionResult< List<AccountDto>> GetSubAccountList([FromQuery(Name = "account_id")]string accountId)
        {
            return accountService.GetSubAccountList(accountId);
        }
        #endregion
        
        #region 删除子账户
        /// <summary>
        /// 删除子账户
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        [HttpDelete("[action]")]
        [ProducesResponseType(typeof(bool), 200)]
        public ActionResult< bool> DeleteSubAccount([FromQuery(Name = "account_id")]string accountId)
        {
            return accountService.DeleteSubAccount(accountId);
        }
        #endregion

        #region 移动子账户
        /// <summary>
        /// 移动子账户
        /// </summary>
        /// <param name="account_id"></param>
        /// <param name="parent_account_id"></param>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(AccountDto), 200)]
        public ActionResult<AccountDto> MoveSubAccount(string account_id,string parent_account_id)
        {
            return accountService.MoveAccount(account_id, parent_account_id);
        }
        #endregion

    }
}